<!DOCTYPE html>
<html lang="zh-CN">
<!--浏览器搞笑标题-->
<script type="text/javascript" src="/js/FunnyTitle.js"></script>






<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/binblog/img/binblog.ico">
  <link rel="icon" type="image/png" href="/binblog/img/binblog.ico">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="leo-bin">
  <meta name="keywords" content="">
  <title>如何用Java设计一个简单的生产者消费者 - 阿斌的个人博客</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/binblog/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/dracula.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/binblog/css/main.css" />

<!-- 自定义样式保持在最底部 -->


<meta name="generator" content="Hexo 4.2.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/binblog/">&nbsp;<strong>Abin的Blog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/binblog/img/6.webp') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-05-31 00:40">
      2020年5月31日 凌晨
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2.2k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      26
       分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-post-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-post-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
              <p class="note note-info">
                
                  本文最后更新于：2020年6月2日 晚上
                
              </p>
            
            <article class="markdown-body">
              <h1><strong>生产者消费者</strong></h1>
<h3>本次给大家分享的是如何使用Java编写一个简易的生产者消费者模板！</h3>
<p><strong>【以下都简称生产者消费者模式为PV模式，P叫做生产者，V叫做消费者】</strong></p>
<h2 id="什么是生产者-消费者？"><a class="header-anchor" href="#什么是生产者-消费者？"></a><strong>什么是生产者-消费者？</strong></h2>
<p><strong>说起生产者和消费者大家其实并不陌生。</strong></p>
<p><strong>早就在学习操作系统的时候我们就知道了如何使用信号量的PV操作来实现进程之间的通信。</strong></p>
<p><strong>PV操作本质上就是生产者消费者模式的核心所在！</strong></p>
<h3 id="PV操作"><a class="header-anchor" href="#PV操作"></a><strong>PV操作</strong></h3>
<p><strong>再说PV操作之前我们有必要引入临界区的概念。</strong></p>
<p><strong>临界区本质上就是一个代码块！任何时候都只有一个进程进入这个代码块执行代码。</strong></p>
<p><strong>那它又是如何实现同一时刻只有一个进程进入呢？</strong></p>
<p><strong>答案就是互斥锁！  Mutex Lock！</strong></p>
<p><strong>当某个进程进入此代码块时会检查临界区的Lock是否被其他进程占有了。</strong></p>
<p><strong>如果被占有了，此时的进程会被挂起进入阻塞队列</strong></p>
<p><strong>如何判断是否被占有呢？答案是资源数!</strong></p>
<p><strong>假设此时的临界区的资源数是 1。</strong></p>
<p><strong>第一个进入此临界区的进程A执行V操作，将资源数 -1，此时的资源数为0。</strong></p>
<p><strong>当有其他进程B想要进入临界区的时候会检查这个资源数，如果为0，则立马被挂起。</strong></p>
<p><strong>当A进程执行完毕之后马上就执行P操作 ，将此时的资源数 +1。</strong></p>
<p><strong>然后B。。。</strong></p>
<div class="hljs"><pre><code class="hljs xml">1.P操作就相当于生产者！将资源数 +1。
2.V操作就相当于消费者！将资源数 -1。</code></pre></div>
<h3 id="为什么要使用PV模式？"><a class="header-anchor" href="#为什么要使用PV模式？"></a>为什么要使用PV模式？</h3>
<p>PV模式有点像日常生活中的工厂和顾客，而超市则就是这两者之间的缓冲区。</p>
<p>我们平时买东西一般都是直接去超市买的，哪有人直接去工厂买的？</p>
<p>工厂只负责生产东西，顾客需要买东西直接去超市买就行。</p>
<p>工厂并不关心超市卖的怎么样，而顾客也不用操心工厂那边是如何生产东西的。</p>
<p>任何一方出了事，都不会直接影响到其任意一方，这就是<strong>耦合</strong>的好处！</p>
<p><strong>不仅如此，通过这种PV模式，在多线程的配合使用下能够大大的提高总体的效率！</strong></p>
<h3 id="PV的概念"><a class="header-anchor" href="#PV的概念"></a>PV的概念</h3>
<p>传统的PV模式一般都有三个模块：<strong>生产者，消费者，还有数据容器</strong>。</p>
<p>这个数据容器就是一个<strong>缓冲区。</strong></p>
<p>生产者往缓冲区中存数据，消费者去里面拿数据。</p>
<p><strong>所以要弄明白PV模式，这个缓冲区是关键！</strong></p>
<p>缓冲区是如何平衡并发的P操作和V操作呢？</p>
<p><strong>答案一般都是使用阻塞队列或者人为加锁来实现！</strong></p>
<h3 id="1）单生产者消费者模式"><a class="header-anchor" href="#1）单生产者消费者模式"></a><strong>1）单生产者消费者模式</strong></h3>
<p><strong><img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/单生产者消费者.jpg" srcset="/binblog/img/loading.gif" style="zoom: 150%;" /></strong></p>
<p>可以看到的是。</p>
<p>对于单一的PV模式来说，我们只需要简单控制P操作和V操作不会操作同一数据就行。</p>
<p>这一点通过加锁很容易实现。</p>
<h3 id="2）多生产者消费者模式"><a class="header-anchor" href="#2）多生产者消费者模式"></a><strong>2）多生产者消费者模式</strong></h3>
<p><strong><img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/多生产者消费者模式.png" srcset="/binblog/img/loading.gif" style="zoom:80%;" /></strong></p>
<p>对于这种多PV模式，需要通过复杂的设计才能实现。</p>
<p>当某个P往里面写的时候需要保证其他的所有P以及V不会影响到此次的P操作。</p>
<p>一个可行的方案就是利用CAS或者Lock将P要写的内存区域锁起来。</p>
<p>但是可想而知，加锁的话这会对性能产生多大的影响？每一个PV在操作之前都要加锁释放锁。</p>
<p>对于这种多PV模式的话，大家可以参考Disruptor的内部实现。</p>
<p>Disruptor内部是采用了一种叫做环形缓冲区的设计，结合一系列非常精妙的设计</p>
<p>使得它基本上没有过多的使用的锁的场景，所以它的性能快的一批！</p>
<p><strong>在这里我提供了一种PV模式的实现</strong></p>
<h2 id="方法一"><a class="header-anchor" href="#方法一"></a><strong>方法一</strong></h2>
<p><strong>我们通过jdk内置的阻塞队列来实现</strong></p>
<p>JDK内置的常用阻塞队列一般就是两个：</p>
<p><strong>ArrayBlockingQueue和LinkedBlockingQueue。</strong></p>
<h2 id="区别"><a class="header-anchor" href="#区别"></a>区别</h2>
<div class="hljs"><pre><code class="hljs tex">看名字就知道了，这里就不细说了，之后会写专门的文章来介绍这两个数据结构的。
不同点：
1.大概就是一个是数组实现的，一个是单向链表实现的。
2.前者通过设置一个ReentrantLock实现整体的线程安全，通过设置takeIndex和putIndex来实现对PV操作的控制。

相同点：
1.内部都是使用ReentrantLock来保证线程安全的。
2.内部都用到了两条件算法Two Condition来实现生产者线程和消费者线程的通信。
3.两条件算法的本质就是当P线程想要放数据的时候发现此时的缓冲区满了，那么此时的P线程就阻塞了。
4.同理的，如果此时的V线程发现现在还没有元素的话，此时的V也会阻塞。
5.当P线程一直到某个V线程取走了一个数据之后，这里的V线程顺带将原先的P线程唤醒。
6.同理，如果此时的P线程线程被唤醒了，当它放了一个元素进去，那么也会顺带将原先阻塞的V线程给唤醒。
7.就是互相通知，互相提醒。</code></pre></div>
<h3 id="参考代码"><a class="header-anchor" href="#参考代码"></a><strong>参考代码</strong></h3>
<p><strong>消费者</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Consumer</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>&#123;
    <span class="hljs-keyword">private</span> BlockingQueue&lt;DataBean&gt; queue;
    <span class="hljs-keyword">private</span> Random random=<span class="hljs-keyword">new</span> Random();
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Consumer</span><span class="hljs-params">(BlockingQueue&lt;DataBean&gt; queue)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.queue = queue;
    &#125;

    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 模拟消费者行为进行消费</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">consume</span><span class="hljs-params">()</span></span>&#123;
        <span class="hljs-comment">//超时时间</span>
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> timeout=<span class="hljs-number">500L</span>;
        <span class="hljs-keyword">try</span> &#123;
            <span class="hljs-comment">//take方法，去队列中拿一条队首数据，如果此时队列中没有数据的话，当前线程会被阻塞，直到队列中有数据</span>
            <span class="hljs-comment">//查看take的源码发现，内部使用可重入式锁来实现：</span>
            <span class="hljs-comment">//这里使用poll方法，如果超过等待时间，返回null，没超过返回队列中的一条队首数据</span>
            <span class="hljs-comment">//这里设置为500毫秒，因为如果不设置的话，一旦队列中产生了第一条数据，，生产者还来不及处理业务就会立马被消费者拿到，产生逻辑错误</span>
            DataBean dataBean=queue.poll(<span class="hljs-number">500L</span>, TimeUnit.MILLISECONDS);
            <span class="hljs-keyword">if</span> (dataBean!=<span class="hljs-keyword">null</span>)&#123;
                System.out.println(<span class="hljs-string">"------数据"</span>+dataBean.getMessage()+<span class="hljs-string">"成功被消费"</span>);
            &#125;
            &#125;<span class="hljs-keyword">catch</span> (InterruptedException e)&#123;
             e.printStackTrace();
            &#125;
        <span class="hljs-comment">//模拟真实的耗时</span>
        <span class="hljs-keyword">try</span>&#123;
            Thread.sleep(random.nextInt(<span class="hljs-number">1000</span>));
        &#125;<span class="hljs-keyword">catch</span> (InterruptedException e)&#123;
            e.printStackTrace();
        &#125;
    &#125;

    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 启动本线程</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">while</span> (<span class="hljs-keyword">true</span>)&#123;
            consume();
        &#125;
    &#125;
&#125;</code></pre></div>
<p><strong>生产者</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Producer</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span></span>&#123;
    <span class="hljs-keyword">private</span> BlockingQueue&lt;DataBean&gt; queue;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> AtomicInteger integer = <span class="hljs-keyword">new</span> AtomicInteger(<span class="hljs-number">0</span>);
    <span class="hljs-keyword">private</span> Random random=<span class="hljs-keyword">new</span> Random();
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Producer</span><span class="hljs-params">(BlockingQueue&lt;DataBean&gt; queue)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.queue = queue;
    &#125;

    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 模拟生产者生产消息</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">produce</span><span class="hljs-params">()</span></span>&#123;
            <span class="hljs-comment">//实际情况可能比较复杂，所以这里模拟数据耗时，随机等待一段时间</span>
            <span class="hljs-keyword">try</span> &#123;
                Thread.sleep(random.nextInt(<span class="hljs-number">1000</span>));
            &#125;<span class="hljs-keyword">catch</span> (InterruptedException e)&#123;
                e.printStackTrace();
            &#125;
            <span class="hljs-comment">//等待队列超时时间</span>
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> timeout=<span class="hljs-number">2000L</span>;
            <span class="hljs-comment">//初始化消息</span>
            DataBean dataBean=<span class="hljs-keyword">new</span> DataBean(String.valueOf(integer.getAndIncrement()));
            <span class="hljs-keyword">try</span>&#123;
                <span class="hljs-comment">//offer方法为，向队列中插入一个对象，如果在插入的过程中等待的时间超过timeout，则返回false，没有超时返回true</span>
                <span class="hljs-keyword">if</span> (!queue.offer(dataBean,timeout, TimeUnit.MILLISECONDS))&#123;
                    System.out.println(<span class="hljs-string">"等待队列时间超时了,超时时间为:"</span>+timeout+<span class="hljs-string">"毫秒"</span>);
                &#125;
                System.out.println(<span class="hljs-string">"------成功生产了一条数据:"</span>+dataBean.getMessage());
            &#125;<span class="hljs-keyword">catch</span> (InterruptedException e)&#123;
                e.printStackTrace();
            &#125;
    &#125;

    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 启动本线程</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">while</span> (<span class="hljs-keyword">true</span>)&#123;
            produce();
        &#125;
    &#125;
&#125;</code></pre></div>
<p><strong>实体bean</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DataBean</span> </span>&#123;
    <span class="hljs-keyword">private</span> String message;
  
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getMessage</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> message;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setMessage</span><span class="hljs-params">(String message)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.message = message;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DataBean</span><span class="hljs-params">(String message)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.message = message;
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">"DataBean&#123;"</span> +
                <span class="hljs-string">"message='"</span> + message + <span class="hljs-string">'\''</span> +
                <span class="hljs-string">'&#125;'</span>;
    &#125;
&#125;</code></pre></div>
<h3 id="测试代码"><a class="header-anchor" href="#测试代码"></a><strong>测试代码</strong></h3>
<p><strong>这里模拟了三个消费者线程和两个生产者线程同时执行PV操作</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        <span class="hljs-comment">//也可以用LinkedBlockingQueue，效果是一样的</span>
        <span class="hljs-comment">//BlockingQueue blockingQueue = new LinkedBlockingQueue(10);</span>
    
        <span class="hljs-comment">//初始化一个容量为10的ArrayBlockingQueue队列</span>
        BlockingQueue queue = <span class="hljs-keyword">new</span> ArrayBlockingQueue(<span class="hljs-number">10</span>);
        <span class="hljs-comment">//初始化一个固定大小为5个线程的线程池</span>
        ExecutorService poolExecutor = Executors.newFixedThreadPool(<span class="hljs-number">5</span>);
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) &#123;
            Consumer consumer = <span class="hljs-keyword">new</span> Consumer(queue);
            poolExecutor.submit(consumer);
        &#125;
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">5</span>; i++) &#123;
            Producer producer = <span class="hljs-keyword">new</span> Producer(queue);
            poolExecutor.submit(producer);
        &#125;
    &#125;</code></pre></div>
<h3 id="测试结果"><a class="header-anchor" href="#测试结果"></a><strong>测试结果</strong></h3>
<img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/image-20200602222315030.png" srcset="/binblog/img/loading.gif" alt="image-20200602222315030" style="zoom:80%;" />
<h2 id="方法二"><a class="header-anchor" href="#方法二"></a><strong>方法二</strong></h2>
<p>其实在了解了JDK内部阻塞队列的原理之后其实我们可以自己手动实现一个阻塞队列。</p>
<p>有时间我会将自己手写ArrayBlockingQueue和LinkedBlockingQueue的过程也发上来。</p>
<p>其实很好理解的，对于jdk内部的 JUC包，其实它的灵魂就是AQS框架。</p>
<p>只要明白了AQS，基本上所有的并发api你都能够掌握啦！</p>
<h2 id="总结"><a class="header-anchor" href="#总结"></a><strong>总结</strong></h2>
<p><strong>1.本次给大家介绍了两个生产者消费者的模板。</strong></p>
<p><strong>2.加油！</strong></p>
<h2 id="参考"><a class="header-anchor" href="#参考"></a><strong>参考</strong></h2>
<p><strong>1.<a href="http://ifeve.com/producers-and-consumers-mode/" target="_blank" rel="noopener">http://ifeve.com/producers-and-consumers-mode/</a></strong></p>
<p><strong>2.<a href="https://www.cnblogs.com/chentingk/p/6497107.html" target="_blank" rel="noopener">https://www.cnblogs.com/chentingk/p/6497107.html</a></strong></p>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/binblog/categories/%E7%AE%97%E6%B3%95/">算法</a>
                    
                  </div>
                
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/binblog/2020/05/31/%E5%88%86%E5%B8%83%E5%BC%8F%E5%9C%BA%E6%99%AF%E4%B8%8B%E7%9A%84%E5%85%A8%E5%B1%80%E5%94%AF%E4%B8%80id%E7%94%9F%E6%88%90%E6%96%B9%E6%A1%88/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">分布式场景下的全局唯一id生成方案</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/binblog/2020/05/30/%E8%AE%BE%E8%AE%A1%E4%B8%80%E4%B8%AA%E6%8A%A2%E7%BA%A2%E5%8C%85%E7%AE%97%E6%B3%95/">
                        <span class="hidden-mobile">如何设计一个抢红包算法</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script defer src="https://cdn.staticfile.org/valine/1.4.14/Valine.min.js" ></script>

  <script type="text/javascript">
    var oldLoadVa = window.onload;
    window.onload = function () {
      oldLoadVa && oldLoadVa();

      new Valine({
        el: "#vcomments",
        app_id: "vsanVmkaurLHyq2Xey9odo5V-gzGzoHsz",
        app_key: "v2hMMe4Mzz3mqpy9jwd7qx8B",
        placeholder: "说点什么吧！",
        path: window.location.pathname,
        avatar: "retro",
        meta: ["nick","mail","link"],
        pageSize: "10",
        lang: "zh-CN",
        highlight: true,
        recordIP: false,
        serverURLs: "",
      });
    };
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://valine.js.org" target="_blank" rel="nofollow noopener noopener">comments
      powered by Valine.</a></noscript>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- LeanCloud 统计PV -->
        <span id="leancloud-site-pv-container" style="display: none">
            总访问量 
            <span id="leancloud-site-pv"></span>
             次
          </span>
      
      
        <!-- LeanCloud 统计UV -->
        <span id="leancloud-site-uv-container" style="display: none">
            总访客数 
            <span id="leancloud-site-uv"></span>
             人
          </span>
      

    
  </div>


    
  <!-- 备案信息 -->
  <div class="beian">
    <a href="http://beian.miit.gov.cn/" target="_blank"
       rel="nofollow noopener">京ICP证123456号</a>
    
      <a
        href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=12345678"
        rel="nofollow noopener"
        class="beian-police"
        target="_blank"
      >
        <span class="beian-police-sep">&nbsp;|&nbsp;</span>
        
          <img src="/binblog/img/police_beian.png" srcset="/binblog/img/loading.gif" alt="police-icon" />
        
        <span>京公网安备12345678号</span>
      </a>
     
  </div>


    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/binblog/js/debouncer.js" ></script>
<script  src="/binblog/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/binblog/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/binblog/js/clipboard-use.js" ></script>



  <script defer>
  (function () {
    // 查询存储的记录
    function getRecord(Counter, target) {
      return new Promise(function (resolve, reject) {
        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({target})))
          .then(resp => resp.json())
          .then(({results, code, error}) => {
            if (code === 401) {
              throw error;
            }
            if (results && results.length > 0) {
              var record = results[0];
              resolve(record);
            } else {
              Counter('post', '/classes/Counter', {target, time: 0})
                .then(resp => resp.json())
                .then((record, error) => {
                  if (error) {
                    throw error;
                  }
                  resolve(record);
                }).catch(error => {
                console.error('Failed to create', error);
                reject(error);
              });
            }
          }).catch((error) => {
          console.error('LeanCloud Counter Error:', error);
          reject(error);
        });
      })
    }

    // 发起自增请求
    function increment(Counter, incrArr) {
      return new Promise(function (resolve, reject) {
        Counter('post', '/batch', {
          "requests": incrArr
        }).then((res) => {
          res = res.json();
          if (res.error) {
            throw res.error;
          }
          resolve(res);
        }).catch((error) => {
          console.error('Failed to save visitor count', error);
          reject(error);
        });
      });
    }

    // 构建自增请求体
    function buildIncrement(objectId) {
      return {
        "method": "PUT",
        "path": `/1.1/classes/Counter/${ objectId }`,
        "body": {
          "time": {
            '__op': 'Increment',
            'amount': 1
          }
        }
      }
    }

    // 校验是否为有效的 UV
    function validUV() {
      var key = 'LeanCloud_UV_Flag';
      var flag = localStorage.getItem(key);
      if (flag) {
        // 距离标记小于 24 小时则不计为 UV
        if (new Date().getTime() - parseInt(flag) <= 86400000) {
          return false;
        }
      }
      localStorage.setItem(key, new Date().getTime().toString());
      return true;
    }

    function addCount(Counter) {
      var enableIncr = 'true' === 'true' && window.location.hostname !== 'localhost';
      var getterArr = [];
      var incrArr = [];

      // 请求 PV 并自增
      var pvCtn = document.querySelector('#leancloud-site-pv-container');
      if (pvCtn || enableIncr) {
        var pvGetter = getRecord(Counter, 'site-pv').then((record) => {
          incrArr.push(buildIncrement(record.objectId))
          var ele = document.querySelector('#leancloud-site-pv');
          if (ele) {
            ele.innerText = record.time + 1;
            if (pvCtn) {
              pvCtn.style.display = 'inline';
            }
          }
        });
        getterArr.push(pvGetter);
      }

      // 请求 UV 并自增
      var uvCtn = document.querySelector('#leancloud-site-uv-container');
      if (uvCtn || enableIncr) {
        var uvGetter = getRecord(Counter, 'site-uv').then((record) => {
          var vuv = validUV();
          vuv && incrArr.push(buildIncrement(record.objectId))
          var ele = document.querySelector('#leancloud-site-uv');
          if (ele) {
            ele.innerText = record.time + (vuv ? 1 : 0);
            if (uvCtn) {
              uvCtn.style.display = 'inline';
            }
          }
        });
        getterArr.push(uvGetter);
      }

      // 如果是文章，请求文章的浏览数，并自增
      if ('true' === 'true') {
        var viewCtn = document.querySelector('#leancloud-post-views-container');
        if (viewCtn || enableIncr) {
          var target = decodeURI('/binblog/2020/05/31/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8Java%E8%AE%BE%E8%AE%A1%E4%B8%80%E4%B8%AA%E7%94%9F%E4%BA%A7%E8%80%85%E6%B6%88%E8%B4%B9%E8%80%85/');
          var viewGetter = getRecord(Counter, target).then((record) => {
            incrArr.push(buildIncrement(record.objectId))
            if (viewCtn) {
              var ele = document.querySelector('#leancloud-post-views');
              if (ele) {
                ele.innerText = (record.time || 0) + 1;
                viewCtn.style.display = 'inline';
              }
            }
          });
          getterArr.push(viewGetter);
        }
      }

      // 如果启动计数自增，批量发起自增请求
      if (enableIncr) {
        Promise.all(getterArr).then(() => {
          incrArr.length > 0 && increment(Counter, incrArr);
        })
      }
    }

    var app_id = 'vsanVmkaurLHyq2Xey9odo5V-gzGzoHsz'
    var app_key = 'v2hMMe4Mzz3mqpy9jwd7qx8B'
    var server_url = ''

    function fetchData(api_server) {
      var Counter = (method, url, data) => {
        return fetch(`${ api_server }/1.1${ url }`, {
          method,
          headers: {
            'X-LC-Id': app_id,
            'X-LC-Key': app_key,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };

      addCount(Counter);
    }

    var api_server = app_id.slice(-9) !== '-MdYXbMMI' ? server_url : `https://${ app_id.slice(0, 8).toLowerCase() }.api.lncldglobal.com`;

    if (api_server) {
      fetchData(api_server);
    } else {
      fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
        .then(resp => resp.json())
        .then(({api_server}) => {
          fetchData('https://' + api_server);
        });
    }
  })();
</script>






  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "如何用Java设计一个简单的生产者消费者&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/binblog/js/local-search.js" ></script>
  <script>
    var path = "/binblog/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>





  

  
    <!-- MathJax -->
    <script>
      MathJax = {
        tex: {
          inlineMath: [['$', '$'], ['\\(', '\\)']]
        },
        options: {
          renderActions: {
            findScript: [10, doc => {
              document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
                const display = !!node.type.match(/; *mode=display/);
                const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
                const text = document.createTextNode('');
                node.parentNode.replaceChild(text, node);
                math.start = { node: text, delim: '', n: 0 };
                math.end = { node: text, delim: '', n: 0 };
                doc.math.push(math);
              });
            }, '', false],
            insertedScript: [200, () => {
              document.querySelectorAll('mjx-container').forEach(node => {
                let target = node.parentNode;
                if (target.nodeName.toLowerCase() === 'li') {
                  target.parentNode.classList.add('has-jax');
                }
              });
            }, '', false]
          }
        }
      };
    </script>

    <script async src="https://cdn.staticfile.org/mathjax/3.0.5/es5/tex-svg.js" ></script>

  













  

  

  

  

  

  





<script src="/binblog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/binblog/live2dw/assets/koharu.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
